<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>文件上传下载, 支持文件夹</title>
    <meta name="description" content="" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="" />
    <style>
      #uploadFile, #uploadFilebox {
        display: inline-block;
        outline: none;
        cursor: pointer;
        text-align: center;
        text-decoration: none;
        font: 14px/100% Arial, Helvetica, sans-serif;
        padding: 5px 2px 4px;
        text-shadow: 0 1px 1px rgba(0, 0, 0, 0.3);
        -webkit-border-radius: 5px;
        -moz-border-radius: 5px;
        border-radius: 5px;
        -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
        -moz-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
        color: #f5f5f5;
        border: solid 1px #0076a3;
        background: #0095cd;
        background: -webkit-gradient(
          linear,
          left top,
          left bottom,
          from(#0095cc),
          to(#00678e)
        );
        background: -moz-linear-gradient(top, #00adee, #00678e);
        filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00adee', endColorstr='#00678e');
      }
      #uploadFile:hover ,#uploadFilebox:hover {
        background: #007ead;
        background: -webkit-gradient(
          linear,
          left top,
          left bottom,
          from(#00678e),
          to(#0095cc)
        );
        background: -moz-linear-gradient(top, #00678e, #0095cc);
        filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00678e', endColorstr='#0095cc');
      }
      .uploadFlexBox {
        margin-top: 200px;
        display: flex;
        justify-content: space-around;
      }
      #downloadArea{
        border:  1px dashed lightblue;
        min-width:  300px;
        min-height: 400px;
      }
    </style>
    <!-- <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js"></script> -->
  </head>
  <body>
    <div class="uploadFlexBox">
      <button id="uploadFile" onclick="easyUpload(undefined, false)">点击上传</button>
      <button id="uploadFilebox" onclick="easyUpload(undefined,true)">
        点击上传文件夹
      </button> 
    </div>
    <!-- 下载树状图系列 -->
    <p>下载区域: 点击下载， 文件直接下载，目录下载当前目录下所有的文件（以压缩包形式）</p>
    <div id="downloadArea"> </div>
  </body>
  <script>
 
    var downloadBox = document.getElementById("downloadArea");
    var resultObj; // upload 回调的全局存储对象
    var base_url = "http://192.168.6.168:8889/"; // 上传upload 用
    // 固定url，根据后端数据递归形成树形结构
    var fixedUrl =
      "http://192.168.6.168:8889/file-service/affix/folder/download?filePath="; // 下载用
      // treeData 后台树形结构 ，webkitdirectory 是否是文件夹
    function generateTree(treeData, webkitdirectory) {
      var html = "";
      function loop(treeData) {
        // 目录自身
        var dirSelf = `<ul><li style="display:${webkitdirectory ? 'block': 'none'}"><a href="${fixedUrl + treeData.path}" >${
         treeData.name
        }</a></li>`;
        html = html + dirSelf;
        // 生成同级别的文件列表
        var fileList = treeData.fileList;
        if (fileList) {
          fileList.forEach((file) => {
            html += `<li><a href="${fixedUrl + file.path}">${
              file.name
            }</a></li>`;
          });
        }
        // 子目录
        var subDirArr = treeData.folderList;
        if (subDirArr && subDirArr.length) {
          for (var i = 0; i < subDirArr.length; i++) {
            loop(subDirArr[i]);
          }
        }
        html += "</ul>";
      }
      loop(treeData);
      return html;
    }
    /* 
      Bool multiple 是否支持多选， 默认支持
      Bool webkitdirectory， 控制是否支持文件夹上传，默认为false
     */
    function easyUpload(multiple , webkitdirectory) {
      var input = document.createElement("input");
      input.type = "file";
      input.multiple = (multiple == undefined) ? true : Boolean(multiple) ; // 支持多选
      input.webkitdirectory = webkitdirectory; // 文件夹上传
      input.click();
      input.onchange = function () {
        var form = new FormData();
        var files = input.files;
        // console.log(files);
        //文件夹名称
        if (input.webkitdirectory) {
          var relativePath = files[0].webkitRelativePath;
          var folderName = relativePath.split("/")[0];
          // console.log(relativePath, folderName);
        }

        for (var i = 0; i < files.length; i++) {
          form.append("files", files[i], webkitdirectory?files[i].webkitRelativePath:files[i].name); //第一个参数是后台读取的请求key值
        }
        // console.log(form.getAll("files"))
        // form.append("token", "你的token");
        var xhr = new XMLHttpRequest();
        var actionUpload = base_url + "file-service/affix/folder/upload"; //上传服务的接口地址
        // var action = "http:127.0.0.1:3000/upload"
        xhr.open("POST", actionUpload);
        xhr.send(form); //发送表单数据
        xhr.onreadystatechange = function () {
          if (xhr.readyState == 4 && xhr.status == 200) {
            var data = JSON.parse(xhr.responseText);
            if (data.code == 200) {
              resultObj = data.data;
              var html = generateTree(resultObj, webkitdirectory);
               //  文件下载
               downloadBox.innerHTML = html;
            } else {
              alert("文件上传失败");
            }
          }
          
        };
      };
    }

    //  文件下载
    // $("#downloadBox").html(generateTree(responseData.data));

    //  });
  </script>
</html>
